package com.itheima.controller;

import com.itheima.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String pathname;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        File file1 = new File(pathname);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String filename = (UUID.randomUUID().toString())+"."+extension;
        file.transferTo(new File(pathname+filename));
        return Result.success(filename);
    }
    @GetMapping("download")
    public void download(String name,HttpServletResponse response ) throws Exception {
        log.info(name);
        FileInputStream fileinputStream = new FileInputStream(new File(pathname+name));
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");
        IOUtils.copy(fileinputStream,outputStream);
        outputStream.close();
        fileinputStream.close();
    }

}
